package com.ah._02global;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.List;

/**
 * 生产者
 */
public class Produce {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //创建生产者对象
        DefaultMQProducer dmp = new DefaultMQProducer("global_produce_group");
        //设置命名空间地址
        dmp.setNamesrvAddr("192.168.19.132:9876");
        //启动生产者
        dmp.start();

        for (int i = 0; i < 10; i++) {
            //创建消息对象
            Message message = new Message("global_topic", "", ("hello mq global"+i).getBytes());
            //发送消息
            SendResult result = dmp.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    return list.get(1);
                }
            },1);
            System.out.println("result = " + result);
            String msg = new String(message.getBody());
            System.out.println("msg = " + msg);
        }

        //关闭生产者impletopic
        dmp.shutdown();
    }
}
